package daosimp;

import java.util.ArrayList;
import java.util.List;

import modelo.Alumno;
import modelo.Evaluacion;
import modelo.Examen;

import org.hibernate.Query;
import org.hibernate.Transaction;

import util1.HibernateUtil;
import daos.ExamenDAO;

public class ExamenDAOIMP implements ExamenDAO {

	private Transaction tx;

	@Override
	public void registrarExamen(Examen examen) {
		try {
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.save(examen);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			throw ex;
		}
	}

	@Override
	public void modificarExamen(Examen examen) {
		try {
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.update(examen);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			throw ex;
		}
	}

	@Override
	public void eliminarExamen(Examen examen) {
		try {
			tx = HibernateUtil.session.beginTransaction();
			HibernateUtil.session.delete(examen);
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
			throw ex;
		}
	}

	@Override
	public List<Examen> listarTotalExamenes() {
		List<Examen> examenes = new ArrayList<Examen>();
		try {
			tx = HibernateUtil.session.beginTransaction();
			String hql = "FROM Examen";
			Query query = HibernateUtil.session.createQuery(hql);
			if (!query.list().isEmpty()) {
				examenes = query.list();
			}
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
		}
		return examenes;
	}

	@Override
	public Examen obtenerExamenxEvaluacion(Evaluacion evaluacion, Alumno alumno) {
		Examen examen = null;
		try {
			tx = HibernateUtil.session.beginTransaction();
			String hql = "FROM Examen where evaluacion='"
					+ evaluacion.getEvaluacionId() + "' and alumno='"
					+ alumno.getIdAlumno() + "'";
			Query query = HibernateUtil.session.createQuery(hql);
			if (!query.list().isEmpty()) {
				examen = (Examen) query.list().get(0);
			}
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
		}
		return examen;
	}

	@Override
	public List<Examen> obtenerExamenesxAlumno(Alumno alumno) {
		List<Examen> examenes = new ArrayList<Examen>();
		try {
			tx = HibernateUtil.session.beginTransaction();
			String hql = "FROM Examen where alumno='"+alumno.getIdAlumno()+"'";
			Query query = HibernateUtil.session.createQuery(hql);
			if (!query.list().isEmpty()) {
				examenes = query.list();
			}
			tx.commit();
		} catch (Exception ex) {
			tx.rollback();
		}
		return examenes;
	}

}
